<template>
  <div class="categories">
    <!-- 添加分类按钮 -->
    <el-button @click="showAdd" type="success" plain class="addBtn">添加分类</el-button>

    <!-- 分类表格 -->
    <el-table
      :data="categoryList"
      style="width: 100%"
      row-key="cat_id"
      v-loading="loading"
      element-loading-text="拼命加载..."
      element-loading-background="rgba(255,255,255,0.8)"
      class="categoryTable"
    >
      <el-table-column prop="cat_name" label="分类名称"></el-table-column>
      <el-table-column prop label="是否有效">
        <template v-slot="{ row }">{{ row.cat_deleted ? "否" : "是" }}</template>
      </el-table-column>
      <el-table-column prop="cat_level" label="层级"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button icon="el-icon-edit" type="primary" size="small" plain></el-button>
          <el-button @click="delCategory(row.cat_id)" icon="el-icon-delete" type="danger" size="small" plain></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!-- 添加分类对话框 -->
    <el-dialog title="添加分类" :visible.sync="addVisible" width="40%" @close="closeAdd">
      <el-form
        :model="addForm"
        :rules="rules"
        ref="addForm"
        label-width="100px"
        class="demo-addForm"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="父级名称" prop="cat_pid">
          <el-cascader
            ref="cascader"
            clearable
            :props="props"
            v-model="addForm.cat_pid"
            :options="options"
            placeholder="请选择"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCategory">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      categoryList: [{}],
      pagenum: 1,
      pagesize: 5,
      total: 0,
      loading: false,
      addVisible: false,
      addForm: {
        cat_pid: [],
        cat_name: '',
        cat_level: ''
      },
      rules: {
        cat_name: [
          {
            required: true,
            message: '分类名称不能为空',
            trigger: ['blur', 'change']
          }
        ]
      },
      options: [],
      props: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true // 断开各个级之间的关联
      }
    }
  },
  created () {
    this.getCategoryList()
  },
  methods: {
    async getCategoryList () {
      this.loading = true
      const { data, meta } = await this.$axios.get(`categories`, {
        params: {
          type: 3,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      })
      if (meta.status === 200) {
        this.categoryList = data.result
        this.total = data.total
        this.loading = false
        // console.log(data)
      } else {
        this.$message.error(meta.msg)
        this.loading = false
      }
    },
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.pagenum = 1
      this.getCategoryList()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.pagenum = val
      this.getCategoryList()
    },
    // 显示添加框
    async showAdd () {
      this.addVisible = true
      const { meta, data } = await this.$axios.get('categories?type=2')
      if (meta.status === 200) {
        this.options = data
      }
    },
    // 添加分类
    async addCategory () {
      try {
        await this.$refs.addForm.validate()
        const arrPid = this.addForm.cat_pid
        const { meta } = await this.$axios.post(`categories`, {
          cat_name: this.addForm.cat_name,
          cat_pid: arrPid[arrPid.length - 1] || 0,
          cat_level: this.addForm.cat_pid.length
        })
        if (meta.status === 201) {
          this.$message.success(meta.msg)
          this.addVisible = false
          this.getCategoryList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 关闭添加框
    closeAdd () {
      this.$refs.addForm.resetFields()
    },
    // 删除分类
    async delCategory (id) {
      try {
        await this.$confirm('确认删除该分类吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const { meta } = await this.$axios.delete(`categories/${id}`)
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          this.getCategoryList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        this.$message.error(e)
      }
    }
  },
  watch: {
    'addForm.cat_pid' () {
      this.$refs.cascader.dropDownVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.addBtn {
  margin-bottom: 10px;
}
.categoryTable {
  margin-bottom: 10px;
}
</style>
